﻿using System;
using System.Collections.Generic;
using System.Configuration;
using System.IO;
using System.Linq;
using System.Runtime.Remoting.Channels;
using System.Runtime.Remoting.Channels.Tcp;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Text;

namespace NabNetWeb
{
    public partial class _Rfid : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            string nabSerialNumber = Request.QueryString["sn"];
            string mailDirectory = ConfigurationManager.AppSettings["RfidDirectory"];
            string rfidSerialNumber = Request.QueryString["t"];

            #region remoting call
            try
            {
                TcpChannel channel = new TcpChannel();
                if (ChannelServices.GetChannel(channel.ChannelName)==null)
                {
                    ChannelServices.RegisterChannel(channel, false);
                }
                NabNetLib.Remoting.Interface.IRemoteNabNet remoteOperation = (NabNetLib.Remoting.Interface.IRemoteNabNet)Activator.GetObject(
                    typeof(NabNetLib.Remoting.Interface.IRemoteNabNet),
                    "tcp://localhost:1069/RemoteNabNet");

                remoteOperation.RfidAction(nabSerialNumber, rfidSerialNumber);
            }
            catch (Exception ex) {
            //todo log
                string s = ex.ToString();
            }
            #endregion


            if (!Path.IsPathRooted(mailDirectory))
            {
                mailDirectory = Context.Server.MapPath(mailDirectory);
            }

            if (!Directory.Exists(mailDirectory))
            {
                Directory.CreateDirectory(mailDirectory);
            }

            string fileName = nabSerialNumber + "_" + DateTime.Now.ToString("yyyyMMdd_HHmmss") + ".rfid.txt";
            fileName = Path.Combine(mailDirectory, fileName);

            using (FileStream fs = new FileStream(fileName, FileMode.Create))
            {
                byte[] buffer = Encoding.UTF8.GetBytes(Request.Url.ToString());
                fs.Write(buffer, 0, buffer.Length);

                int length = (int)Request.InputStream.Length;
                buffer = new byte[length];
                Request.InputStream.Read(buffer, 0, length);
                fs.Write(buffer, 0, length);
            }
        }
    }
}
